<template>
  <div class="cmt-contain">
    <h1>发表评论</h1>

    <hr>

    <textarea placeholder="请输入要发表的内容(最多120个字)" maxlength="120" v-model="msg"></textarea>

    <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>

    <div class="cmt-content" v-for="(item,i) in commentsList" :key="item.add_time">
      <div class="top">
        <span>第{{i+1}}楼</span>
        <span>用户:{{item.user_name}}</span>
        <span>发表时间:{{item.add_time | timeFormat}}</span>
      </div>
      <div class="bottom content">
        {{item.content==="undefined"?"该用户很懒，嘛也没说":item.content}}
      </div>
    </div>
  
    <!-- 加载更多 -->
    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from 'mint-ui';
export default {
  data(){
    return{
      commentsList:[],
      pageindex:1,
      msg:"",
    }
  },
  created(){
    this.getComments();
  },
  methods:{
    // 获取评论内容的方法
    getComments(){
      this.$http.get("http://www.liulongbin.top:3005/api/getcomments/"+this.id+"?pageindex="+this.pageindex)
      .then((result)=>{
        if(result.body.status===0){
          this.commentsList=this.commentsList.concat(result.body.message);
        }else{
          Toast("获取失败");
        }
      })
    },
    // 加载更多评论
    getMore(){
      this.pageindex+=1;
      this.getComments();
    },
    // 向服务器发送post的请求发送数据
    postComment(){
      // 判断content是否为空
      if(this.msg.trim().length===0){
        Toast("评论不允许为空")
      }else{
        this.$http.post("http://www.liulongbin.top:3005/api/postcomment/"+this.id,{content:this.msg.trim()}).then((result)=>{
          if(result.body.status===0){
            let cmt = {
              user_name:"匿名用户",
              add_time:Date.now(),
              content:this.msg.trim()
            };
              this.commentsList.unshift(cmt);
              this.msg="";
          }else{
          Toast("数据上传失败")
           }
        })
      }
    }
  },
  props:["id"]
}
</script>

<style lang="scss" scoped>
  .cmt-contain{
    margin-bottom: 20px;
    h1{
      font-size:20px; 
    }
    textarea{
      margin-bottom:0px; 
      height: 85px;
    }
    .cmt-content{
      margin-top:5px;
      font-size: 13px;
      .top{
        background: #cccccc;
        padding: 5px 0;
      }
      .bottom{
        padding: 5px 0px;
        text-indent: 2em;
      }
    }
  }
</style>
